package com.gitee.jwds666.fs.utils;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class InetUtils {

    /**
     * 端口是否使用
     * @param port
     * @return
     */
    public static boolean portUsing(int port){
        try {
           Socket socket = new Socket("127.0.0.1",port);
           socket.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    /**
     * 获取有效端口
     * @param defaultPort 默认
     * @param minPort 最小
     * @param maxPort 最大
     * @return
     */
    public static int getValidPort(int defaultPort,int minPort,int maxPort){
        if (minPort <0 || maxPort > 65535 || defaultPort < 0 || defaultPort > 65535){
            throw new IllegalArgumentException("端口错误");
        }
        if (!portUsing(defaultPort)){
            return defaultPort;
        }
        while (minPort <= maxPort){
            if (!portUsing(minPort)){
                return minPort;
            }
            minPort++;
        }
        throw new IllegalArgumentException("没有有效端口");
    }

    /**
     * 获取本机ip
     * @return
     */
    public static List<String> getLocalHostIp(){
        List<String> res = new ArrayList<>();
        try {
            String add = InetAddress.getLocalHost().getHostName();
            InetAddress [] inetAddresses = InetAddress.getAllByName(add);

            for (InetAddress inetAddress : inetAddresses) {
                if (inetAddress.getHostAddress().indexOf(":") == -1){
                    res.add(inetAddress.getHostAddress());
                }
            }

        } catch (UnknownHostException e) {
            return Collections.singletonList("localhost");
        }
        return res;
    }

}
